#!/bin/bash
# by yingnn on Feb-25-2014
set -e

while getopts  ":o:" opts
do
	case  $opts  in
	o)
		out_name=$OPTARG
		;;
	\?)
		echo `basename $0` '[-o chr.fa] in.fa chr'
		exit 1
		;;
	esac
done
shift $(($OPTIND - 1))

if test $# -lt 2; then
	echo `basename $0` '[-o chr.fa] in.fa chr'
	exit 65
fi

let num_plus=$2+1

num0=`cat $1 |grep -m 1 -n -P "^>([C|c]hr)?$2\b" |cut -d : -f 1`
num1=`cat $1 |grep -m1 -n -P "^>([C|c]hr)?${num_plus}\b" |cut -d : -f 1`
let num1=$num1-1

echo chr$2 starts at: $num0 1>&2
echo chr$2 ends at: $num1 1>&2

if test -z "$out_name"; then
filename=chr$2.fa
sed -n "$num0, ${num1}p" $1 > $filename
else
sed -n "$num0, ${num1}p" $1 > $out_name
fi

exit 0
